const qiniu = require('qiniu')
const { accessKey, secretKey, uploadToken, config, baseUrl, basePath } = require('./qiniu.config')

/**
 * @desciption 通用处理方法 
 */
const _handleCallback = (resolve, reject) => {
  return (respErr, respBody, respInfo) => {
    if (respErr) {
      throw respErr;
    }
    if (respInfo.statusCode === 200) {
      resolve(respBody);
    } else {
      reject({
        statusCode: respInfo.statusCode,
        body: respBody
      })
    }
  }
}

// 上传文件 返回url
function uploadFile(
  localFilePath = '',
  newFilename = '', // 这里最好是随机数字+英文字母加上扩展名
) {
  const formUploader = new qiniu.form_up.FormUploader(config)
  const putExtra = new qiniu.form_up.PutExtra()
  // 处理路径问题
  const path = basePath + newFilename
  return new Promise((resolve, reject) => {
    formUploader.putFile(uploadToken, path, localFilePath, putExtra, _handleCallback(resolve, reject))
  }) 
}

// 调用示例函数
// uploadFile('C:/Users/Administrator/Desktop/唯唯诺诺表情包.png', 'weiweinuonuo123233.png').then(res => {
//   const { key } = res
//   console.log(baseUrl + key)
// })